<template>
  <div class="upload">
    <!-- <el-alert
      :closable="false"
      :title="`支持jpg、jpeg、png格式，单次可最多选择${limit}张图片，每张不可大于${size}M，如果大于${size}M会自动为您过滤`"
      type="info"
    /> -->
    <ul class="el-upload-list el-upload-list--picture-card">
      <draggable v-model="imgfileList" @end="onSort">
        <li v-for="(item, index) in imgfileList" :key="item.uid" class="el-upload-list__item is-success animated">
          <img alt="" class="el-upload-list__item-thumbnail" :src="item.url" style="object-fit: fill" />
          <i class="el-icon-close"></i>
          <span class="el-upload-list__item-actions">
            <!-- 预览 -->
            <span class="el-upload-list__item-preview" @click="handlePreview(item)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <!-- 删除 -->
            <span class="el-upload-list__item-delete" @click="Removeimg(index)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </li>
        <el-upload
          ref="upload"
          v-loading="loading"
          accept="image/png, image/jpeg"
          :action="action"
          :auto-upload="true"
          :before-upload="beforeupload"
          :class="{ hide: imgfileList.length == limit }"
          :data="data"
          :file-list="imgfileList"
          :headers="headers"
          :limit="limit"
          list-type="picture-card"
          :multiple="true"
          :name="name"
          :on-change="handleChange"
          :on-error="handleError"
          :on-exceed="handleExceed"
          :on-preview="handlePreview"
          :on-progress="handleProgress"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :show-file-list="false"
          style="display: inline"
        >
          <i slot="trigger" class="el-icon-plus"></i>
          <el-dialog append-to-body title="查看大图" :visible.sync="dialogVisible">
            <div>
              <img alt="" :src="dialogImageUrl" width="100%" />
            </div>
          </el-dialog>
        </el-upload>
      </draggable>
    </ul>

    <!--  <el-button type="danger" @click="handleClose">清空</el-button>
    <el-button :loading="loading" size="small" style="margin-left: 10px" type="success" @click="submitUpload">上传</el-button> -->
  </div>
</template>

<script>
  import draggable from 'vuedraggable'
  export default {
    name: 'VabUpload',
    components: { draggable },
    props: {
      name: {
        type: String,
        default: 'file',
        required: true,
      },
      limit: {
        type: Number,
        default: 50,
        required: true,
      },
      size: {
        type: Number,
        default: 1,
        required: true,
      },
      fileList: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        progress: 0, // 保存当前的上传进度
        notifyInstance: null, // 保存notify实例
        dialogImageUrl: '',
        /*  hideUploadBtn: false, */
        dialogVisible: false,
        loading: false,
        imgNum: 0,
        imgSuccessNum: 0,
        imgErrorNum: 0,
        action: 'https://www.wandilease.com:8007/Sys/UploadImg',
        headers: {},
        data: { appId: 'WDZJ', filePath: this.name },
        imgfileList: this.fileList,
      }
    },
    watch: {
      fileList(newvel) {
        this.imgfileList = newvel
      },
    },
    /* created() {
        this.hideUploadBtn = this.fileList.length == this.limit
      },
      updated() {
        this.hideUploadBtn = this.fileList.length == this.limit
      }, */
    methods: {
      /* UploadImage() {
          var formData = new FormData()
          formData.append('file', this.imgfileList[0].raw)
          UploadFiles(this.data, formData)
            .then((response) => {
              console.log(response, '成功')
              // 处理返回的数据
            })
            .catch((error) => {
              console.log(error, '失败')
              // 处理错误
            })
        }, */
      onSort() {
        this.$emit('changeList', this.imgfileList)
      },
      submitUpload() {
        this.$refs.upload.submit()
      },
      handleProgress(event) {
        this.loading = true
        let num = event.percent / 100
        let percentage = `${(num * 100).toFixed(2)}%`

        if (this.notifyInstance) {
          // 更新提示内容和进度
          this.notifyInstance.message = `正在上传中... 当前上传进度${percentage} 当前上传失败数:${this.imgErrorNum}张`
        } else {
          // 创建新的notify实例
          this.notifyInstance = this.$notify.info({
            title: '提示',
            message: `正在上传中... 当前上传进度${percentage} 当前上传失败数:${this.imgErrorNum}张`,
            duration: 0,
          })
        }
      },
      beforeupload(file) {
        if (file.size > 1048576 * this.size) {
          this.imgfileList.map((item, index) => {
            if (item === file) {
              fileList.splice(index, 1)
              this.$notify({
                title: '提示',
                message: `文件大小超过${size}M!`,
                type: 'success',
              })
            }
          })
        }
      },
      handleChange(file, fileList) {
        this.imgfileList = fileList
        this.allImgNum = fileList.length
      },
      async handleSuccess(response, file, fileList) {
        if (response.code != 1000) {
          this.handleError(response, file, fileList)
        }

        this.imgfileList = await fileList.filter(function (item) {
          return item.response.code == 1000
        })
        this.$emit('succestList', fileList, file)
        this.notifyInstance.close()
        this.imgNum = this.imgNum + 1
        this.imgSuccessNum = this.imgSuccessNum + 1
        setTimeout(() => {
          this.$refs.upload.clearFiles()
        }, 100)
        this.$notify({
          title: '提示',
          message: `上传完成! 共${this.imgfileList.length}张图片`,
          type: 'success',
        })
        this.loading = false
      },
      handleError(err, file, fileList) {
        this.notifyInstance.close()
        this.imgNum = this.imgNum + 1
        this.imgErrorNum = this.imgErrorNum + 1
        this.$notify.error({
          title: '错误',
          message: `服务器忙，文件[${file.raw.name}]上传失败,请稍后再试`,
        })
        this.loading = false
      },
      handleRemove(file, fileList) {
        this.imgfileList = fileList
        this.imgNum = this.imgNum - 1
        this.allNum = this.allNum - 1
        this.$emit('changeList', fileList, file)
      },
      handlePreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      Removeimg(index) {
        let img = this.imgfileList[index]
        this.imgfileList.splice(index, 1)
        this.$emit('changeList', this.imgfileList, img)
      },
      handleExceed(files, fileList) {
        this.$baseMessage(
          `当前限制选择 ${this.limit} 个文件，本次选择了
             ${files.length}
             个文件`,
          'error'
        )
      },
      handleClose() {
        this.imgfileList = []
        this.$emit('succestList', this.imgfileList)
        this.allImgNum = 0
        this.imgNum = 0
        this.imgSuccessNum = 0
        this.imgErrorNum = 0
        this.dialogFormVisible = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  .upload {
    position: relative;
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }
    .hide {
      ::v-deep .el-upload--picture-card {
        display: none !important;
      }
    }
    ::v-deep {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px 8px;
        border: 2px dashed #c0ccda;
      }

      .el-upload-list--picture {
        margin-bottom: 20px;
      }

      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px 8px;
        }
      }
      .el-button {
        margin-left: 10px;
      }
    }
  }
</style>
